from django.contrib.auth.backends import ModelBackend
import re

# from mgproject.apps.userapp.models import Users
# 配置过导包路径配置相对
from .models import Users


class MutiAccountLoginAuth(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        # 判断请求是否通过vue组件发送请求
        if request is None:
            try:
                user = Users.objects.get(username=username,is_staff=True)
            except:
                return None
            # 判断密码
            if user.check_password(password):
                return user
        else:
            try:
                # 输入的用户名 有可能是 手机号; 进行多账号校验
                if re.match('^1[35789]\d{9}$',username):
                    user = Users.objects.get(phone=username)
                else:
                    user = Users.objects.get(username=username)
            except Users.DoesNotExist:
                user = None
            # 匹配用户名和密码
            if user and user.check_password(password):
                return user